/**
 * jims
 */

package com.jims.master.modules.base.user.service;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.SpringContextHolder;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.base.user.dao.MasterBaseinfoDao;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterContactinfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.doctor.netHosptial.entity.NetClinic;
import com.jims.master.modules.doctor.netHosptial.service.NetClinicService;
import com.jims.master.modules.sys.entity.SysLoginName;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.SysLoginNameService;
import com.jims.master.modules.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户信息表Service
 * @author jict
 * @version 2017-11-15
 */
@Service
public class MasterBaseinfoService extends CrudService<MasterBaseinfoDao, MasterBaseinfo> {

    @Autowired
    private MasterContactinfoService masterContactinfoService;
    @Autowired
    private MasterDoctorinfoService masterDoctorinfoService;
    @Autowired
    private SysLoginNameService sysLoginNameService;
    @Autowired
    private UserService userService;
    @Autowired
    private NetClinicService netClinicService;

    /**
     * 移动端申请成为医生
     * @param map
     * @author 陈涛
     * @return
     */
    @Transactional(readOnly = false)
    public MasterBaseinfo saveDoctor(Map map){
        /*MasterDoctorinfo masterDoctorinfo = new MasterDoctorinfo();
        userService.updateUserType("2", (String) map.get("openid"));
        User user = userService.findUserDocOpenId((String) map.get("openid"));

        MasterBaseinfo masterBaseinfo = this.get(user.getPersionId());*/

        MasterBaseinfo mb=new MasterBaseinfo();
        mb.setIdCard((String) map.get("idCard"));
//      判断基本信息表是否存在
        MasterBaseinfo masterBaseinfo=dao.getByIdCard(mb);
        if(masterBaseinfo==null){
            masterBaseinfo = new MasterBaseinfo();
            masterBaseinfo.setHeadPath((String) map.get("head_path"));
            masterBaseinfo.setName((String) map.get("name"));
            masterBaseinfo.setSex((String) map.get("sex"));
            masterBaseinfo.setIdCard((String) map.get("idCard"));
            this.save(masterBaseinfo);
        }else{
            int i=0;
            if(masterBaseinfo.getHeadPath()==null||masterBaseinfo.getHeadPath().equals("")){
                masterBaseinfo.setHeadPath((String) map.get("head_path"));
                i+=1;
            }
            if(masterBaseinfo.getName()==null||masterBaseinfo.getName().equals("")){
                masterBaseinfo.setName((String) map.get("name"));
                i+=1;
            }
            if(masterBaseinfo.getSex()==null||masterBaseinfo.getSex().equals("")){
                masterBaseinfo.setSex((String) map.get("sex"));
                i+=1;
            }
            if(i>0){
                this.save(masterBaseinfo);
            }

        }
//      判断基本信息子表是否存在
        MasterContactinfo masterContactinfo=masterContactinfoService.getContacBybaseInfo(masterBaseinfo.getId());
        if(masterContactinfo==null){
            masterContactinfo=new MasterContactinfo();
            masterContactinfo.setMobilePhone((String) map.get("mobile"));
            masterContactinfo.setBaseinfo(masterBaseinfo);
            masterContactinfoService.save(masterContactinfo);
        }else {
            int j=0;
            if(masterContactinfo.getMobilePhone()==null||masterContactinfo.getMobilePhone().equals("")){
                masterContactinfo.setMobilePhone((String) map.get("mobile"));
                j+=1;
            }
            if(masterContactinfo.getBaseinfo()==null||masterContactinfo.getBaseinfo().equals("")){
                masterContactinfo.setBaseinfo(masterBaseinfo);
                j+=1;
            }

            if(j>0){
                masterContactinfoService.save(masterContactinfo);
            }
        }
//      判断医生信息是否存在
        MasterDoctorinfo masterDoctorinfo = masterDoctorinfoService.getDoctorinfoByBaseinfoId(masterBaseinfo.getId());
        if(masterDoctorinfo==null){
            masterDoctorinfo=new MasterDoctorinfo();
            masterDoctorinfo.setMechanism((String) map.get("mechanism"));
            masterDoctorinfo.setParts((String) map.get("parts"));
            masterDoctorinfo.setTitles((String) map.get("titles"));
            masterDoctorinfo.setRegisterPlace((String) map.get("area"));
//            masterDoctorinfo.setDoctorGoodAt((String) map.get("doctor_good_at"));
//            masterDoctorinfo.setDoctorProfile((String) map.get("doctor_profile"));
            masterDoctorinfo.setDocFlag("0");
//            masterDoctorinfo.setWorkPic((String) map.get("work_pic"));
            masterDoctorinfo.setLicencePic((String) map.get("licence_pic"));
            masterDoctorinfo.setTitlePic((String) map.get("title_pic"));
            masterDoctorinfo.setBaseinfo(masterBaseinfo);
            masterDoctorinfoService.save(masterDoctorinfo);
        }else{
            int k=0;
            if(masterDoctorinfo.getMechanism()==null||masterDoctorinfo.getMechanism().equals("")){
                masterDoctorinfo.setMechanism((String) map.get("mechanism"));
                k+=1;
            }

            if(masterDoctorinfo.getParts()==null||masterDoctorinfo.getParts().equals("")){
                masterDoctorinfo.setParts((String) map.get("parts"));
                k+=1;
            }
            if(masterDoctorinfo.getTitles()==null||masterDoctorinfo.getTitles().equals("")){
                masterDoctorinfo.setTitles((String) map.get("titles"));
                k+=1;
            }
            if(masterDoctorinfo.getBaseinfo()==null||masterDoctorinfo.getBaseinfo().equals("")){
                masterDoctorinfo.setBaseinfo(masterBaseinfo);
                k+=1;
            }
            /*if(masterDoctorinfo.getDoctorGoodAt()==null||masterDoctorinfo.getDoctorGoodAt().equals("")){
                masterDoctorinfo.setDoctorGoodAt((String) map.get("doctor_good_at"));
                k+=1;
            }
            if(masterDoctorinfo.getDoctorProfile()==null||masterDoctorinfo.getDoctorProfile().equals("")){
                masterDoctorinfo.setDoctorProfile((String) map.get("doctor_profile"));
                k+=1;
            }*/

                masterDoctorinfo.setDocFlag("0");
                k+=1;

            /*if(masterDoctorinfo.getWorkPic()==null||masterDoctorinfo.getWorkPic().equals("")){
                masterDoctorinfo.setWorkPic((String) map.get("work_pic"));
                k+=1;
            }*/
            if(masterDoctorinfo.getLicencePic()==null||masterDoctorinfo.getLicencePic().equals("")){
                masterDoctorinfo.setLicencePic((String) map.get("licence_pic"));
                k+=1;
            }
            if(masterDoctorinfo.getTitlePic()==null||masterDoctorinfo.getTitlePic().equals("")) {
                masterDoctorinfo.setTitlePic((String)map.get("title_pic"));
                k += 1;
            }
            if(k>0){
                masterDoctorinfoService.save(masterDoctorinfo);
            }
        }

       /* masterBaseinfo.setHeadPath((String) map.get("head_path"));
        masterBaseinfo.setName((String) map.get("name"));
        masterBaseinfo.setSex((String) map.get("sex"));
        this.save(masterBaseinfo);
        //masterDoctorinfo = masterDoctorinfoService.getDoctorinfoByBaseinfoId(user.getPersionId());
        masterDoctorinfo.setMechanism((String) map.get("mechanism"));
        masterDoctorinfo.setParts((String) map.get("parts"));
        masterDoctorinfo.setTitles((String) map.get("titles"));
        masterDoctorinfo.setDoctorGoodAt((String) map.get("doctor_good_at"));
        masterDoctorinfo.setDoctorProfile((String) map.get("doctor_profile"));
        masterDoctorinfo.setDocFlag("0");
        masterDoctorinfo.setWorkPic((String) map.get("work_pic"));
        masterDoctorinfo.setLicencePic((String) map.get("licence_pic"));
        masterDoctorinfo.setTitlePic((String) map.get("title_pic"));
        //masterdoctorinfo.setBaseinfo(masterBaseinfo);
        masterBaseinfo.setId(user.getPersionId());
        masterDoctorinfo.setBaseinfo(masterBaseinfo);*/
//        int i = masterDoctorinfoService.save(masterDoctorinfo);
        int update=userService.updateUserType("2", (String) map.get("openid"),masterBaseinfo.getId());
        if(update>0){
            return masterBaseinfo;
        }else {
            return  null;
        }
    }

   /* *//**
     * 保存(更新)用户信息
     * @param masterBaseinfo
     * @return
     * @author jicunteng
     *//*
    @Transactional(readOnly = false)
    public int saveAll(MasterBaseinfo masterBaseinfo) {
        int i = 0;
        //通过id获取数据库用户数据
        MasterContactinfo masterContactinfo = masterContactinfoService.getContacBybaseInfo(masterBaseinfo.getId());
        MasterContactinfo masterContactinfo1 = masterBaseinfo.getMasterContactinfo();
        masterContactinfo1.setId(masterContactinfo.getId());
        masterContactinfo1.setBaseinfo(masterBaseinfo);
        super.save(masterBaseinfo);
        User user= UserUtils.getUser();
        //个人信息修改后同时要修改网易即时通讯的基本信息，这时需要把user表中的neteaseFlag修改为0,0表示未同步，1表示同步
        user.setNeteaseInfoFlag("0");
        userDao.updateNeteaseInfoFlag(user);
        String idCard=masterBaseinfo.getIdCard();
        String userId=sysLoginNameService.findValidate(idCard);
//      绑定身份证登录

        if(userId!=null&&!(userId.equals(""))){
            logger.debug("登录信息已经存在");
        }else{
            SysLoginName sysLoginName=new SysLoginName();
            sysLoginName.setLoginName(idCard);
            sysLoginName.setType("2");
            sysLoginName.setUser(user);
            sysLoginNameService.save(sysLoginName);
        }
        i = masterContactinfoService.save(masterContactinfo1);
        return i;
    }
    */


    /**
     * 保存用户和角色关联关系
     * @param-userId
     * @param-roleId
     *//*
    @Transactional(readOnly = false)
    public void saveAll(MasterBaseinfo baseInfo, MasterContactinfo contactInfo) {
        //1.保存注册用户基本信息
        save(baseInfo);
        User user = new User();
        //2.将基本信息与登录用户表关联
        user.setPersionId(baseInfo.getId());
        //董毅表结构调整注释
        user.setPassword(StringUtils.entryptPassword("123456"));
        user.setUserType("3");
        user.preInsert();
        userDao.insert(user);
        //保存个人注册联系方式
        contactInfo.setBaseinfo(baseInfo);
        contactInfo.preInsert();
        masterContactinfoDao.insert(contactInfo);
        //给新注册用户默认赋权-普通用户
        SysLoginName sysLoginName = new SysLoginName();
        sysLoginName.setUser(user);
        if (contactInfo.getMobilePhone() != null) {
            sysLoginName.setType("0");
            sysLoginName.setLoginName(contactInfo.getMobilePhone());
        } else {
            if (baseInfo.getIdCard() != null) {
                sysLoginName.setType("2");
                sysLoginName.setLoginName(baseInfo.getIdCard());
            }
        }
        sysLoginNameService.save(sysLoginName);
    }

    *//**
     * 根据身份证号查询是否身份证号已存在
     * @param card
     * @return
     * @author jicunteng
     *//*
    public MasterBaseinfo findByCardNum(String card) {
        return dao.findByCardNum(card);
    }

    *//**
     * 上传头像
     * @param
     * @param
     * @return
     * @throws Exception
     * @author jicunteng
     *//*
    @Transactional(readOnly = false)
    public String savePics(MultipartFile file, HttpServletRequest request) throws Exception {
        String home = request.getSession().getServletContext().getRealPath("");
        String pathImg = "headImage";
        String datePath = DateUtils.formatDate(new Date(), "yyyy/MM/dd");
        //文件路径
        String pathUrl = File.separator + pathImg + File.separator + datePath + File.separator + "headImage";
        //文件名
        String str = UUIDUtil.getUUID();
        String headPath = str + ".";
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        //访问地址url
        pathUrl = pathUrl + File.separator + headPath + fileName;
        File fileTemp = new File(home + pathUrl);
        if (!fileTemp.exists())
            fileTemp.mkdirs();

        file.transferTo(fileTemp);
        //文件名为当前时间
        return pathUrl;
    }

    /**
     * user注册保存基本信息
     * @param sysLoginName 登录基本信息
     * @return sln 看是否成功
     */
    @Transactional(readOnly = false)
    public int userRegister(SysLoginName sysLoginName, MasterContactinfo masterContactinfo) throws IOException {
        MasterBaseinfo masterBaseinfo=sysLoginName.getUser().getMasterBaseinfo();
        this.save(masterBaseinfo);
//        MasterContactinfo masterContactinfo=sysLoginName.getUser().getMasterBaseinfo().getMasterContactinfo();
        masterContactinfo.setBaseinfo(masterBaseinfo);
        masterContactinfoService.save(masterContactinfo);
//        医生信息提交
        if((sysLoginName.getUser().getUserType()).equals("2")){
            MasterDoctorinfo masterDoctorinfo=new MasterDoctorinfo();
            masterDoctorinfo.setRegisterPlace(masterContactinfo.getPlaceAddress());
            masterDoctorinfo.setDoctorNo("100");
            masterDoctorinfo.setBaseinfo(masterBaseinfo);
            masterDoctorinfo.setDocFlag("0");
            masterDoctorinfo.setParts(sysLoginName.getUser().getOrgDept().getDeptCode());
            masterDoctorinfo.setTitles(sysLoginName.getUser().getTitle());
            masterDoctorinfoService.save(masterDoctorinfo);
        }
        sysLoginName.getUser().setPersionId(masterBaseinfo.getId());
        return sysLoginNameService.userRegister(sysLoginName);
    }
    /**
     * 普通用户改变成医生保存基本信息
     * @param user 医生基本信息
     * @return int
     */
    /*@Transactional(readOnly = false)
    public int chageDoctor(User user,String placeAddress){
        MasterBaseinfo masterBaseinfo=user.getMasterBaseinfo();
        this.dao.update(masterBaseinfo);
//        医生信息提交
        if((user.getUserType()).equals("2")){
            MasterDoctorinfo masterDoctorinfo=new MasterDoctorinfo();
            masterDoctorinfo.setRegisterPlace(placeAddress);
            masterDoctorinfo.setDoctorNo("100");
            masterDoctorinfo.setBaseinfo(masterBaseinfo);
            masterDoctorinfo.setDocFlag("0");
            masterDoctorinfo.setParts(user.getOrgDept().getDeptCode());
            masterDoctorinfo.setTitles(user.getTitle());
            masterDoctorinfoService.save(masterDoctorinfo);
        }
        MasterContactinfo masterContactinfo=user.getMasterBaseinfo().getMasterContactinfo();
        masterContactinfo.setBaseinfo(masterBaseinfo);
        masterContactinfoService.update(masterContactinfo);
        return sysLoginNameService.chageDoctor(user);
    }*/

    /***
     * 和用户有医患关系的医生list
     * @param baseInfo
     * @return
     *//*
    public List<MasterBaseinfo> findRecordToDoctors(MasterBaseinfo baseInfo){
        return dao.findRecordToDoctors(baseInfo);
    }

    *//***
     * 和用户有医患关系的患者list
     * @param baseInfo
     * @return
     *//*
    public List<MasterBaseinfo> findRecordToPatients(MasterBaseinfo baseInfo){
        return dao.findRecordToPatients(baseInfo);
    }*/

    /**
     * 根据idcard查找用户信息
     * @param
     * @return
     */
    public MasterBaseinfo getByIdCard(MasterBaseinfo baseInfo){
        return dao.getByIdCard(baseInfo);
    }

    /**
     * 绑定身份证信息
     * @param idCard
     * @return
     * @author jicunteng
     */
    @Transactional(readOnly = false)
    public MasterBaseinfo bindingIdCard(String idCard,String mobile){
        MasterBaseinfo masterBaseinfo=validIDCard(idCard);
//        User user=UserUtils.getUser();
        User user= userService.get(sysLoginNameService.findValidate(mobile));
//      数据库中没有基本信息，新建
        if(masterBaseinfo==null){
            masterBaseinfo=new MasterBaseinfo();
            masterBaseinfo.setIdCard(idCard);
            this.save(masterBaseinfo);
            MasterContactinfo masterContactinfo=new MasterContactinfo();
            masterContactinfo.setBaseinfo(masterBaseinfo);
            masterContactinfo.setMobilePhone(user.getCurrentLogin());
            masterContactinfoService.save(masterContactinfo);
            user.setPersionId(masterBaseinfo.getId());
            userService.updatePersionId(user);
        }else{
//          判断该身份证是否有登录信息，没有的话给user表绑定已存在的信息，有的话不绑定，返回空信息，重新输入身份证绑定
            User oldUser=userService.findUserByPersonId(masterBaseinfo.getId());
            System.out.println("有没有旧的登录信息："+oldUser);
            if(oldUser==null){
                user.setPersionId(masterBaseinfo.getId());
                int i=userService.updatePersionId(user);
                System.out.println("更新是否成功："+i);
//                userService.updatePersionId(masterBaseinfo.getId(),user.getId());
            }else{
                masterBaseinfo=null;
            }
        }
        return masterBaseinfo;
    }
    /**
     * 根据身份证号和主键查询该登录用户身份证号码是否已存在
     * @param idCard
     * @return
     * @author jicunteng
     */
    public MasterBaseinfo validIDCard(String idCard) {
        return dao.validIDCard(idCard);
    }

    public MasterBaseinfo getInfo(String id) {
        return dao.getInfo(id);
    }
    /**
     * 医生添加患者基本信息
     * @param
     * @param
     * @return sln 看是否成功
     */
//    @Transactional(readOnly = false)
    /*public int docAddUser(MasterBaseinfo masterBaseinfo, MasterContactinfo masterContactinfo,DoctorVsPatient doctorVsPatient){
//      判断用户信息是否存在，如果存在只存关系信息
        if(masterBaseinfo!=null&&masterContactinfo!=null){
            this.save(masterBaseinfo);
            masterContactinfo.setBaseinfo(masterBaseinfo);
            masterContactinfoService.save(masterContactinfo);
            doctorVsPatient.setPatientId(masterBaseinfo.getId());
        }
        return doctorVsPatientService.save(doctorVsPatient);
    }*/
    /**
     * 医生添加患者基本信息
     * @param mobile 患者电话号码
     * @param idCard 患者身份证号
     * @param sex 患者性别
     * @param age 患者年龄
     * @param name 患者姓名
     * @param doctorId 医生id
     * @return sln 看是否成功
     */
    @Transactional(readOnly = false)
    public String docAddUser(String mobile, String idCard, String sex, String age, String name, String doctorId){
//      判断用户信息是否存在，如果存在只存关系信息
        MasterBaseinfo masterBaseinfo=null;
        NetClinic netClinic=new NetClinic();
        netClinic.setDoctorid(doctorId);
//		判断身份证信息是否存在，不存在就新添加
        if(StringUtils.isNotBlank(idCard)){
            masterBaseinfo=dao.validIDCard(idCard);
        }
        if(masterBaseinfo!=null){
//			判断已存在的用户名字是否为空
            int i=0;
            if(StringUtils.isNotEmpty(name)){
                masterBaseinfo.setName(name);
                i+=1;
            }
            if(StringUtils.isNotEmpty(sex)){
                masterBaseinfo.setSex(sex);
                i+=1;
            }
            if(StringUtils.isNotEmpty(age)){
                masterBaseinfo.setAge(age);
                i+=1;
            }
            if(i>0){
                i=this.save(masterBaseinfo);
            }
//          判断手机号是否为空
            MasterContactinfo masterContactinfo=masterContactinfoService.getContacBybaseInfo(masterBaseinfo.getId());
            if(masterContactinfo.getMobilePhone()==null||masterContactinfo.getMobilePhone().equals("")){
                masterContactinfo.setMobilePhone(mobile);
                i=masterContactinfoService.save(masterContactinfo);
            }
//          保存医患关系
            netClinic.setPatientId(masterBaseinfo.getId());
            int count=netClinicService.relativity(netClinic);
            if(count==0){
                netClinicService.save(netClinic);
            }
            return masterBaseinfo.getId();
        }else {
//          保存患者基本信息及医患关系
            masterBaseinfo=new MasterBaseinfo();
            if(idCard!=null&&!"".equals(idCard)){
                masterBaseinfo.setIdCard(idCard);
            }
            masterBaseinfo.setName(name);
            masterBaseinfo.setAge(age);
            masterBaseinfo.setSex(sex);
            MasterContactinfo masterContactinfo=new MasterContactinfo();
            masterContactinfo.setMobilePhone(mobile);
            this.save(masterBaseinfo);
            masterContactinfo.setBaseinfo(masterBaseinfo);
            masterContactinfoService.save(masterContactinfo);
            netClinic.setPatientId(masterBaseinfo.getId());
            netClinicService.save(netClinic);
            return masterBaseinfo.getId();
        }
    }
    /**
     * 保存医生和患者之间的关系信息
     * @param doctorVsPatient 医患关系
     * @return sln 看是否成功
     */
//    @Transactional(readOnly = false)
//    public int saveRelativity(DoctorVsPatient doctorVsPatient){ return doctorVsPatientService.save(doctorVsPatient);}

    /**
     * 查询我的患者
     * @return
     */
    public List<MasterBaseinfo> getMyPatient(String id,Integer pageSize,Integer pageNum){
        Integer start =null;
        Integer end =null;
        if(pageSize!=null&&pageNum!=null&&pageSize>=1&&pageNum>0){
            start = pageSize*(pageNum-1);
            end = pageSize*pageNum;
        }
        return dao.getMyPatient(id,start,end);
    }

    /**
     * 医生添加患者基本信息
     * @param mobile 患者电话号码
     * @param idCard 患者身份证号
     * @param name 患者姓名
     * @return sln 看是否成功
     */
    @Transactional(readOnly = false)
    public MasterBaseinfo addRelativesFriends(String mobile, String idCard,String name){
//      判断用户信息是否存在，如果存在只存关系信息
        MasterBaseinfo masterBaseinfo=null;
//		判断身份证信息是否存在，不存在就新添加
        masterBaseinfo=dao.validIDCard(idCard);
        if(masterBaseinfo!=null){
//			判断已存在的用户名字是否为空
            int i=0;
            if(masterBaseinfo.getName()==null||masterBaseinfo.getName().equals("")){
                masterBaseinfo.setName(name);
                i+=1;
            }
            if(i>0){
                i=this.save(masterBaseinfo);
            }
//          判断手机号是否为空
            MasterContactinfo masterContactinfo=masterContactinfoService.getContacBybaseInfo(masterBaseinfo.getId());
            if(masterContactinfo!=null){
                if(masterContactinfo.getMobilePhone()==null||masterContactinfo.getMobilePhone().equals("")){
                    masterContactinfo.setMobilePhone(mobile);
                    masterContactinfoService.save(masterContactinfo);
                }
            }else{
                masterContactinfo = new MasterContactinfo();
                masterContactinfo.setMobilePhone(mobile);
                masterContactinfo.setBaseinfo(masterBaseinfo);
                masterContactinfoService.save(masterContactinfo);
                masterBaseinfo.setMasterContactinfo(masterContactinfo);
            }
            return masterBaseinfo;
        }else {
//          不存在该身份证亲友时重新生成
            masterBaseinfo=new MasterBaseinfo();
            masterBaseinfo.setIdCard(idCard);
            masterBaseinfo.setName(name);
            MasterContactinfo masterContactinfo=new MasterContactinfo();
            masterContactinfo.setMobilePhone(mobile);
            this.save(masterBaseinfo);
            masterContactinfo.setBaseinfo(masterBaseinfo);
            masterContactinfoService.save(masterContactinfo);
            masterBaseinfo.setMasterContactinfo(masterContactinfo);
            return masterBaseinfo;
        }
    }
}